import json
import os.path

from .compBase import TBaseComp
import  threading
import requests


import pymysql
import pymssql
from DBUtils.PooledDB import PooledDB
import redis
"""
# pip install pymysql
# pip install pymssql
# pip install DBUtils==1.3  --- 特别要注意
# pip install -i https://pypi.doubanio.com/simple paho-mqtt
"""

class TCompRedis(TBaseComp):
    def __init__(self):
        super().__init__()
        self.componentKey = 'redis'
        self.pools = {}
        self.handlers={
            "getDict":self.getDict
        }

    def getPool(self, code):
        pool = None
        status = 0
        try:
            if code in self.pools.keys():
                pool = self.pools[code]
                status = 1
            elif code in self.settings.keys():
                settingItem = self.settings[code]
                ps={
                    "host":settingItem['host'],
                    "port":settingItem['port'],
                    "db":settingItem['db']
                }
                r = redis.StrictRedis(**ps)
                if r.ping():
                    pool = r
                    self.pools[code] = pool
                    status = 1
                    print('connect redis success.')
                else:
                    status = 1002
            else:
                status = 1001
                print("pool Code is error.", code)
        except Exception as er:
            print(er)
        return pool, status
    def getDict(self, code , key):
        res = {
            "status":0 ,
            "result":{}
        }
        try:
            pool ,status = self.getPool(code)
            if status== 1 :
                resData = pool.hgetall(key)
                res = {
                    "status":1 ,
                    "result": resData
                }

        except Exception as er:
            print(er)
        return res
compRedis = TCompRedis()
compRedis.regist()